package controller

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"time"
	"wangchunguang_blog/model"
	"wangchunguang_blog/service"
	"wangchunguang_blog/system"
	"wangchunguang_blog/utils"
)

// 订阅首页
func SubscriberIndex(c *gin.Context) {
	subscribers, _ := service.ListSubscriber(false)
	user, _ := c.Get(CONTEXT_USER_KEY)
	c.HTML(http.StatusOK, "admin/subscriber.html", gin.H{
		"subscribers": subscribers,
		"user":        user,
		"comments":    service.MustListUnreadComment(),
	})
}

// 获取订阅页面

func SubscribeGet(c *gin.Context) {
	count, _ := service.CountSubscriber()
	c.HTML(http.StatusOK, "other/subscribe.html", gin.H{
		"total": count,
	})
}

// 订阅
func Subscribe(c *gin.Context) {
	mail := c.PostForm("mail")
	var err error
	if len(mail) > 0 {
		var subscriber *model.Subscriber
		subscriber, err = service.GetSubscriberBySigneture(mail)
		if err != nil {
			if !subscriber.VerifyState && utils.GetCurrentTime().After(subscriber.OutTime) {
				err = sendActiveEmail(subscriber)
				if err == nil {
					count, _ := service.CountSubscriber()
					c.HTML(http.StatusOK, "other/subscribe.html", gin.H{
						"message": "subscribe succeed.",
						"total":   count,
					})
					return
				}
			} else if subscriber.VerifyState && !subscriber.SubscribeState { //已经认证了的 没有订阅
				subscriber.SubscribeState = true
				err = service.UpdateSubscriber(subscriber)
				if err == nil {
					err = errors.New("订阅成功")
				}
			} else {
				// 邮件已经激活 或者没有收到邮件信箱
				err = errors.New("邮件已经激活 或者没有收到邮件信箱")
			}
		} else {
			subscriber := &model.Subscriber{
				Email: mail,
			}
			err = service.InsertSubscriber(subscriber)
			if err == nil {
				err = sendActiveEmail(subscriber)
				if err == nil {
					count, _ := service.CountSubscriber()
					c.HTML(http.StatusOK, "other/subscribe.html", gin.H{
						"message": "订阅成功",
						"total":   count,
					})
					return
				}
			}

		}

	} else {
		err = errors.New("请输入邮箱账号")
	}
	count, _ := service.CountSubscriber()
	c.HTML(http.StatusOK, "other/subscribe.html", gin.H{
		"message": err.Error(),
		"total":   count,
	})
}

// 添加邮箱
func sendActiveEmail(subscriber *model.Subscriber) (err error) {
	uuid := utils.UUID()
	duration, _ := time.ParseDuration("30m")
	subscriber.OutTime = utils.GetCurrentTime().Add(duration)
	subscriber.SecretKey = uuid
	signature := utils.Md5(subscriber.Email + uuid + subscriber.OutTime.Format("201911171252"))
	subscriber.Signature = signature
	err = sendMail(subscriber.Email, "[blog]邮箱验证", fmt.Sprintf("%s/active?sid=%s", system.GetConfiguration().Domain, signature))
	if err != nil {
		return
	}
	err = service.UpdateSubscriber(subscriber)
	return
}

// 有效的订阅
func ActiveSubscriber(c *gin.Context) {
	var (
		err        error
		subscriber *model.Subscriber
	)

	sid := c.Query("sid")
	if sid == "" {
		HandleMessage(c, "激活连接有误，请重新获取")
		return
	}
	subscriber, err = service.GetSubscriberBySigneture(sid)
	if err != nil {
		HandleMessage(c, "激活连接有误，请重新获取")
		return
	}
	if !utils.GetCurrentTime().Before(subscriber.OutTime) {
		HandleMessage(c, "激活连接已经过期，请重新获取")
		return
	}
	subscriber.VerifyState = true
	subscriber.OutTime = utils.GetCurrentTime()
	err = service.UpdateSubscriber(subscriber)
	if err != nil {
		HandleMessage(c, fmt.Sprintf("激活失败！ %s", err.Error()))
		return
	}
	HandleMessage(c, "激活成功")
}

// 退订订阅
func UnSubscribe(c *gin.Context) {
	sid := c.Query("sid")
	if sid == "" {
		HandleMessage(c, "内部服务器错误")
		return
	}
	subscriber, err := service.GetSubscriberBySigneture(sid)
	if err != nil || !subscriber.VerifyState || !subscriber.SubscribeState {
		HandleMessage(c, "退定失败.")
		return
	}
	subscriber.SubscribeState = false
	err = service.UpdateSubscriber(subscriber)
	if err != nil {
		HandleMessage(c, fmt.Sprintf("退订失败 %s", err.Error()))
		return
	}
	HandleMessage(c, "退订成功")
}

// 获取退订信息
func GetUnSubcribeUrl(subscriber *model.Subscriber) (string, error) {
	uuid := utils.UUID()
	signature := utils.Md5(subscriber.Email + uuid)
	subscriber.SecretKey = uuid
	subscriber.Signature = signature
	err := service.UpdateSubscriber(subscriber)
	return fmt.Sprintf("%s/unsubscribe?sid=%s", system.GetConfiguration().Domain, signature), err
}

// 邮箱为空时  发送给所有的订阅者
func SubscriberPost(c *gin.Context) {
	var (
		err error
		res = gin.H{}
	)
	defer writeJSON(c, res)
	mail := c.PostForm("mail")
	subject := c.PostForm("subject")
	body := c.PostForm("body")
	if len(mail) > 0 {
		err = sendMail(mail, subject, body)
	} else {
		err = sendEmailToSubscribers(subject, body)
	}
	if err != nil {
		res["message"] = err.Error()
		return
	}

	res["succeed"] = true

}

// 发送邮件
func sendEmailToSubscribers(subject, body string) (err error) {

	var (
		subs   []*model.Subscriber
		emails = make([]string, 0)
	)
	subs, err = service.ListSubscriber(true)
	if err != nil {
		return
	}
	for _, sub := range subs {
		emails = append(emails, sub.Email)
	}
	if len(emails) == 0 {
		err = errors.New("没有订阅信息")
		return
	}

	err = sendMail(strings.Join(emails, ";"), subject, body)
	return
}
